<template>
  <div>
    <a-card class="card" :bordered="false" :style="`min-height: ${cardMinHeight}px;`">
      <!--弹窗0 新增按钮-->
      <a-modal
          destroyOnClose
          class="addModal"
          v-model='addModal'
          width='1100px'
          :title="isAdd?'新增':title"
          @cancel="handleCancel0"
          @ok="submitAndSaveDetailMore"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 150px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: center">
            <div style="width: 95%;">
              <a-form-model :model="basicForm"  layout="inline" ref="basicFormRef" :rules="rules">
                <a-form-model-item
                    required
                    label="编码"
                    prop="code"
                    style="margin-left: 35px">
                  <a-input style='width: 350px;height: 32px;' v-model.trim="basicForm.code" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    required
                    label="名称"
                    prop="name"
                    style="margin-left: 46px">
                  <a-input style='width: 350px;height: 32px;' v-model.trim="basicForm.name"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="安装位置"
                    prop="location"
                    style="margin-left: 18px">
                  <a-input style='width: 350px;height: 32px;' v-model.trim="basicForm.location"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="设备组状态"
                    prop="deviceStatus"
                    style="margin-left: 16px">
                  <a-select
                      style='width: 350px;height: 32px;'
                      allow-clear
                      @change="basicFormStatusChange"
                      v-model.trim="basicForm.status"
                      :disabled="!canBeEdited || !isAdd"
                  >
                    <a-select-option
                        v-for='item in basicForm.statusList2'
                        :key='item.code'
                        :value='item.code'
                    >{{item.description}}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item
                    label="设备组等级"
                    prop="deviceRating"
                    style="margin-left: 4px">
                  <a-select
                      style='width: 350px;height: 32px;'
                      allow-clear
                      @change="basicFormGradeChange"
                      v-model.trim="basicForm.device_grade_id"
                      :disabled="!canBeEdited || !isAdd"
                  >
                    <a-select-option
                        v-for='(item,index) in basicForm.groupGradeList'
                        :key='index'
                        :value='item.id'
                    >{{item.name}}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item
                    label="设备类型"
                    prop="deviceType"
                    style="margin-left: 30px">
                  <a-select
                      allow-clear
                      style='width: 350px;height: 32px;'
                      @change="basicFormTypeChange"
                      v-model.trim="basicForm.type"
                      :disabled="!canBeEdited || !isAdd"
                  >
                    <a-select-option
                        v-for='(item,index) in basicForm.typeList'
                        :key='index'
                        :value='item.id'
                    >{{item.name}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-form-model>
            </div>
          </div>
          <!--标签页-->
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;border-top: 1px solid #ddd;">
            <a-tabs type="card" :activeKey="tabKey" @change="callback" :tabBarGutter="tabBarGutter" :tabBarStyle="tabBarStyle" style="width: 100%;">
              <a-tab-pane key="1" tab="子设备" :force-render="true">
                <div style="width: 100%;display: flex;flex-direction: row;">
                  <div style="width: 100%;">
                      <div style="display: flex;justify-content: space-between;margin-bottom: 10px;">
                        <a-popover trigger="click" placement="bottom" :overlayStyle="{ width: '350px' }">
                          <template slot="content">
                            <p class="aPopover" v-for="(item,index) in codeSearchList" :key="index"  @click="changeCode(item)" >{{'code:'+item.code+',name:'+item.name}}</p>
                          </template>
                            <a-input style='width: 350px;height: 32px;'
                                     @change="getDeviceByCode" placeholder="*编码(输入搜索设备)"
                                     @click="getDeviceByCode"
                                     allowClear
                                     v-model.trim="addFormOfNewDevice.code"
                                     :disabled="!canBeEdited || !isAdd"></a-input>
                        </a-popover>


                        <a-input style='width: 350px;height: 32px;' placeholder="*名称" v-model.trim="addFormOfNewDevice.name" disabled></a-input>
                        <div style="width: 247px;display: flex;  justify-content:right">
                          <a-button type="primary" style="margin-right: 15px" @click="clearAddMessage" :disabled="!canBeEdited || !isAdd">重置</a-button>
                          <a-button type="primary" @click="addSubDevice" :disabled="!canBeEdited || !isAdd|| !this.addFormOfNewDevice.code || !this.addFormOfNewDevice.name">添加</a-button>
                        </div>

                      </div>
                    <a-table
                        :columns="key1Columns"
                        :data-source="addDeviceList"
                        :pagination="key1Pagination"
                        @change="onChangeKey1"
                        :showPagination="true"
                        :loading="tableLoading01"
                        :rowKey="(record1) => {return record1.index}"
                        :scroll="{x:true,y: 165 }"
                    >
                      <template slot="action" slot-scope="record1">
                        <a-popconfirm title="确定删除?" @confirm="() => delAddDeviceData(record1)">
                          <a>删除</a>
                        </a-popconfirm>
                      </template>
                    </a-table>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </a-spin>

      </a-modal>

      <!--子设备-->
      <a-modal
          destroyOnClose
          class="subModal"
          v-model='subModal'
          width='1100px'
          :title="isAdd?'子设备':title"
          @cancel="handleCancel1"
          @ok="saveGroupMessage"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 200px;display: flex;flex-direction: row;padding: 10px 24px 10px 24px;justify-content: center">
            <div style="width: 95%;">
              <a-form-model :model="basicForm"  layout="inline" ref="basicFormRef" :rules="rules">
                <a-form-model-item
                    required
                    label="编码"
                    prop="code"
                    style="margin-left: 35px">
                  <a-input style='width: 350px;height: 32px;' v-model.trim="basicForm.code" :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    required
                    label="名称"
                    prop="name"
                    style="margin-left: 46px">
                  <a-input style='width: 350px;height: 32px;' v-model.trim="basicForm.name"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="安装位置"
                    prop="location"
                    style="margin-left: 18px">
                  <a-input style='width: 350px;height: 32px;' v-model.trim="basicForm.location"  :disabled="!canBeEdited || !isAdd"></a-input>
                </a-form-model-item>
                <a-form-model-item
                    label="设备组状态"
                    prop="deviceStatus"
                    style="margin-left: 16px">
                  <a-select
                      style='width: 350px;height: 32px;'
                      allow-clear
                      @change="basicFormStatusChange"
                      v-model.trim="basicForm.status_description"
                      :disabled="!canBeEdited || !isAdd"
                  >
                    <a-select-option
                        v-for='item in basicForm.statusList2'
                        :key='item.code'
                        :value='item.code'
                    >{{item.description}}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item
                    label="设备组等级"
                    prop="deviceRating"
                    style="margin-left: 4px">
                  <a-select
                      style='width: 350px;height: 32px;'
                      allow-clear
                      @change="basicFormGradeChange"
                      v-model.trim="basicForm.group_grade_id"
                      :disabled="!canBeEdited || !isAdd"
                  >
                    <a-select-option
                        v-for='(item,index) in basicForm.groupGradeList'
                        :key='index'
                        :value='item.id'
                    >{{item.name}}</a-select-option>
                  </a-select>
                </a-form-model-item>
                <a-form-model-item
                    label="设备类型"
                    prop="deviceType"
                    style="margin-left: 30px">
                  <a-select
                      allow-clear
                      style='width: 350px;height: 32px;'
                      @change="basicFormTypeChange"
                      v-model.trim="basicForm.type"
                      :disabled="!canBeEdited || !isAdd"
                  >
                    <a-select-option
                        v-for='(item,index) in basicForm.typeList'
                        :key='index'
                        :value='item.id'
                    >{{item.name}}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-form-model>
            </div>
          </div>
          <!--标签页-->
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;border-top: 1px solid #ddd;">
            <a-tabs type="card" :activeKey="tabKey" @change="callback" :tabBarGutter="tabBarGutter" :tabBarStyle="tabBarStyle" style="width: 100%;">
              <a-tab-pane key="1" tab="子设备" :force-render="true">
                <div style="width: 100%;display: flex;flex-direction: row;">
                  <div style="width: 100%;">

                    <a-table
                        :columns="key1Columns"
                        :data-source="key1Data"
                        :pagination="key1Pagination"
                        @change="onChangeKey1"
                        :showPagination="true"
                        :loading="tableLoading01"
                        :rowKey="(record1) => {return record1.index}"
                        :scroll="{x:true,y: 165 }"
                    >
                      <template slot="action" slot-scope="record1">
                        <a-popconfirm title="确定删除?" @confirm="() => delKey1DataFalse(record1)">
                          <a>删除</a>
                        </a-popconfirm>
                      </template>
                    </a-table>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </a-spin>

      </a-modal>

      <page-head-area>
        <div class="extra" style="width: 200px;display: flex;justify-content: space-around">
          <a-button icon="plus-circle" v-auth="`insert`" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;"
          @click="add()">新增</a-button>

          <a-popconfirm title="确定删除?"
                        ok-text="确定"
                        cancel-text="取消"
                        @confirm="delSelectGroupData">
            <a-button icon="delete" v-auth="`delete`" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">删除</a-button>
          </a-popconfirm>

        </div>
      </page-head-area>

      <div class="queryBox">
        <a-form-model layout="inline" :model='queryForm' ref="queryFormRef" class='query' style='display: flex;flex-wrap: wrap;'>
          <a-form-model-item
              class='optionTitle'
              label="编码"
              prop="code"
              style="margin-left: 0px"
          >
            <a-input style='width: 200px;height: 32px' v-model='queryForm.code'  v-auth="`query`"></a-input>
          </a-form-model-item>
          <a-form-model-item
              class='optionTitle'
              label="名称"
              prop="name"
          >
            <a-input style='width: 200px;height: 32px' v-model='queryForm.name'  v-auth="`query`"></a-input>
          </a-form-model-item>


          <a-form-model-item
              label="状态"
              prop="status"
              style=""
              ref="statusRef"
          >
            <a-select
                :is-multiple="false"
                style='width: 150px'
                allow-clear
                v-model.trim='queryForm.mask_status'
                v-auth="`query`"
            >
              <a-select-option
                  v-for='(item,index) in basicForm.statusList'
                  :key='index'
                  :value='item.code'
              >{{item.description}}</a-select-option>
            </a-select>
          </a-form-model-item>


          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="reset" v-auth="`query`">
              重置
            </a-button>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="filter" v-auth="`query`">
              搜索
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="dataBox">
        <a-table
            :columns="columns"
            :data-source="data"
            :pagination="false"
            :loading="tableLoading"
            :rowKey="(recordS) => {return recordS.id}"
            :scroll="{ x: 1000, y: 500 }"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <template slot="action" slot-scope="record">
            <a v-auth="`query`" @click="subDevice(record)">子设备</a>
            <a-divider type="vertical"/>
            <a v-auth="`query`">备品</a>
          </template>
        </a-table>

      </div>
      <a-pagination
          @change="onChangePage"
          @showSizeChange="showSizeChange"
          :total="pagination.total"
          :showSizeChanger="true"
          :showQuickJumper="true"
          :defaultPageSize="pagination.defaultPageSize"
          :pageSize="pagination.page_size"
          :pageSizeOptions="pagination.pageSizeOptions"
          :current="pagination.current"
          :showTotal="pagination.showTotal"
          style="width: 100%;display: flex;flex-direction: row;justify-content: flex-end;margin-top: 15px"
      ></a-pagination>
    </a-card>
  </div>
</template>

<script>

import {mapGetters} from "vuex";
import PageHeadArea from "../module/pageHeadArea.vue";
import pagination from "ant-design-vue/lib/pagination";
import storage from "store";
import {DEPT_ID, ORGANIZATION_ID, USER_TOKEN} from "@/store/mutation-types";
import axios from "axios";
import moment from "moment";
import {
  file_import, file_upload,
  get_employee_list,
  get_extended_define, get_asset_file_list, get_supplier, get_unit_list, download_file,
  get_organization_list,
  delete_asset, get_asset_list, save_asset, update_asset,
  get_category_type_list, get_organization_profile_list, get_template_list, update_extend
} from "@/services/manage";
import {get_device_group_list} from "../../services/deviceManagement";
import {
  deleteDeviceGroup,
  deleteDeviceGroupRelation,
  getDeviceGroupList, getDeviceGroupRelationList,
  getDeviceList,
  getDeviceTypeList,
  getGroupGradeList,
  getUserNameById, saveDeviceGroup, saveDeviceGroupRelation
} from "../../utils/interface";
import {message} from "ant-design-vue";
const data = []
const key1Data=[]

const key1Columns =[
  { title: '编码', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '名称', width: 120, align:'center',dataIndex: 'name', key: 'name'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action' }
  }
]

const columns = [
  { title: '设备组编码', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '设备组名称', width: 120, align:'center',dataIndex: 'name', key: 'name'},
  { title: '类型', width: 120, align:'center',dataIndex: 'type_name', key: 'type_name'},
  { title: '状态', width: 120, align:'center',dataIndex: 'status_description', key: 'status_description'},
  { title: '等级', width: 120, align:'center',dataIndex: 'group_grade_name', key: 'group_grade_name'},
  { title: '设备位置', width: 120, align:'center',dataIndex: 'location', key: 'location'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: "userAuthority",
  components: {PageHeadArea},
  data() {
    return {
      selectedRowKeys: [],
      tableLoading01:false,
      addDeviceList:[],
      codeSearchList:[],
      subModal:false,
      addFormOfNewDevice:{
        id:'',
        code:'',
        name:'',
      },
      key1Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
      key1Data,
      key1Columns,
      rules:{
        code: [{required: true, message: '请输入编码', trigger: 'blur'}],
        name: [{required: true, message: '请输入名称', trigger: 'blur'}],
        device_type_id: [{required: false, message: '请选择设备类型', trigger: 'blur'}],
        device_grade_id: [{required: false, message: '请选择设备等级', trigger: 'blur'}],
        location: [{required: false, message: '请输入安装位置', trigger: 'blur'}],
        create_user:[{required: false, message: '请输入创建人', trigger: 'blur'}],

      },
      saveForm:{
        code: '',
        name: '',
        location: '',
        status: '',
        group_grade_id: '',
        type: '',
      },
      //基础表
      basicForm:{
        status_description:'',
        create_user_name:'',
        typeList:[],
        statusList2:[
          { code: 1, description: "正常运行" },
          { code: 2, description: "正在检修" },
          { code: 3, description: "正常停机" },
          { code: 4, description: "故障停机" },
          { code: -1, description: "组内没有设备/组内设备没有任何状态值" }
        ],//状态列表
        statusList:[
          {code:null,description: "不限"},
          { code: 1, description: "正常运行" },
          { code: 2, description: "正在检修" },
          { code: 3, description: "正常停机" },
          { code: 4, description: "故障停机" },
          { code: -1, description: "组内没有设备/组内设备没有任何状态值" }
        ],//状态列表
        groupGradeList:[],
        code: '',
        create_time: '',
        create_user: '',
        delete_time: '',
        delete_user: '',
        group_grade_id: '',
        id: '',
        location: '',
        name: '',
        status: '',
        type: '',
        update_time: '',
        update_user: ''
      },
      axiosSource: null,
      tabKey: '1',
      title:'',
      tabBarGutter: 0,
      tabBarStyle: {
        color: 'rgba(0, 0, 0, 0.85)'
      },
      bodyStyle: {
        'padding': '0px 24px 0px 24px',
        'font-size': '14px',
        'line-height': '1.5',
        'word-wrap': 'break-word',
      },
      cardMinHeight: 0,
      queryForm: {
        code: '',
        name: '',
        mask_status: undefined,
      },
      statusList: [
        // {id: 1, name: '待采购', code: '0', type: 'use_status'},
        {id: 1, name: '正常运行', code: '1',type: 'use_status'},
        {id: 2, name: '不正常运行', code: '2',type: 'use_status'},
      ],
      data,
      columns,
      pagination: {
        total: 0,
        page_size: 10,
        defaultPageSize: 10,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['10', '20', '50', '100', '500'],
      },
      tableLoading: false,
      addModal: false,
      canBeEdited: false, //是否可编辑
      isAdd: false, //是否为新增
      spinning: false,

      canBeQuery:false, //是否可查询


    }
  },
  watch: {},
  authorize: {
    delFalseList:[],//待删除列表
    add: 'insert',
    getAssetLedgerList: 'query',
    reset: 'query',
    query: 'query',
    detail: 'query',
    edit: 'update',
    del: 'delete',
    check: 'check',
  },
  computed: {
    ...mapGetters(['getCardMinHeight']),
  },
  created() {
    this.cardMinHeight = this.getCardMinHeight
  },
  async mounted() {
    //起始
    // this.axiosSource = axios.CancelToken.source();
    //等级
    await getGroupGradeList().then(res => {
      this.basicForm.groupGradeList=res
    })
    //type
    await getDeviceTypeList().then(res => {
      this.basicForm.typeList=res
    })
    await this.initialize()

  },
  methods: {
    onSelectChange(selectedRowKeys) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    addSubDevice(){
      //查重
      let index = this.addDeviceList.findIndex(item => item.id === this.addFormOfNewDevice.id);
      if(index===-1){
        this.addDeviceList.push({
          id: this.addFormOfNewDevice.id,
          code:this.addFormOfNewDevice.code,
          name:this.addFormOfNewDevice.name
        })
        this.clearAddMessage()
      }else{
        message.error('不能重复添加')
      }

    },
    delAddDeviceData(record){
      const index = this.addDeviceList.findIndex(item => item === record);
      if (index !== -1) {
        this.addDeviceList.splice(index, 1);
      }
    },
    clearAddMessage(){
      this.addFormOfNewDevice={
        id:'',
        code:'',
        name:''
      }
      this.codeSearchList=[]
    },
    // 分页切换
    onChangeKey1 (pagination) {
      this.key1Pagination.current = pagination.current
      this.key1Pagination.page_size = pagination.pageSize
      this.key1Pagination.page = pagination.current
    },
    //初始化
    async initialize(params) {
      this.tableLoading = true
      this.data = []
      const paramsAll = Object.assign({}, params, {
        "page": this.pagination.page,
        "page_size": this.pagination.page_size
      });
      //获取数据
      await get_device_group_list(paramsAll).then(res => {
        console.log(res)
        //res处理
        if(res.data.code === '1000'){
          this.pagination.total = res.data.extension.total+(this.pagination.current-1)*this.pagination.page_size
          res.data.data.forEach(item => {
            item['type_name'] = this.basicForm.typeList.find(type => type.id === item.type)?.name || '';
            item['status_description'] = this.basicForm.statusList.find(status => status.code === item.status)?.description || '';
            item['group_grade_name'] = this.basicForm.groupGradeList.find(groupGrade => groupGrade.id === item.group_grade_id)?.name || '';
          })
        }
        this.data=res.data.data
      })
      this.tableLoading = false
    },
    onChangePage (page, pageSize) {
      this.pagination.current = page
      this.pagination.page_size = pageSize
      this.pagination.page = page
      this.initialize()
    },
    showSizeChange(current, size){
      this.pagination.page_size = size
      this.pagination.current = current
      this.pagination.page = current
      this.initialize()
    },

    async filter() {
      //筛选
      this.pagination.page = 1
      this.pagination.current = 1
      this.pagination.page_size = 10
      this.tableLoading = true
      await this.initialize({
        'code': this.queryForm.code,
        'name': this.queryForm.name,
        'status': this.queryForm.mask_status,

      })
      this.tableLoading = false;
    },
    callback (key) { // assetCode
      this.tabKey = key
    },
    basicFormGradeChange(value){
      this.basicForm.group_grade_id=value
    },
    basicFormStatusChange(value){
      this.basicForm.status=value
      this.basicForm.status_description=this.basicForm.statusList.find(status => status.code === value)?.description || '';
    },
    basicFormTypeChange(value){
      this.basicForm.device_type_id=value
    },
    async getDeviceByCode() {
      await getDeviceList({'code':this.addFormOfNewDevice.code}).then(res => {
        this.codeSearchList = []
        res.slice(0, 10).forEach(item => {
          this.codeSearchList.push({
            id: item.id,
            code: item.code,
            name: item.name
          })
        })
      })
    },
    changeCode(item){
      this.addFormOfNewDevice.id=item.id
      this.addFormOfNewDevice.code=item.code
      this.addFormOfNewDevice.name=item.name
      this.codeSearchList=[]
    },
    // 分页切换
    onChange (pagination) {
      this.pagination.current = pagination.current
      this.pagination.page_size = pagination.pageSize
      this.pagination.page = pagination.current
      this.getAssetLedgerList()
    },
    query() {
      this.pagination.page = 1
      this.pagination.current = 0
      this.pagination.page_size = 10
      this.loading = true
      this.initialize()
    },
    handleCancel0(){
      this.addModal = false
      this.canBeEdited = false
      this.isAdd = false
      this.tabKey = '1'
      this.clearParameters()
    },
    clearParameters() {
      Object.keys(this.basicForm).forEach(key => {
        if (!Array.isArray(this.basicForm[key])) {
          this.basicForm[key] = undefined
        }
      })
      Object.keys(this.saveForm).forEach(key => {
        if (!Array.isArray(this.saveForm[key])) {
          this.saveForm[key] = undefined
        }
      })
      this.key1Data=[]

    },
    handleCancel1(){
      this.delFalseList=[]
      this.subModal = false
      this.canBeEdited = false
      this.isAdd = false
      this.tabKey = '1'
      this.clearParameters()

    },
    async saveGroupMessage() {
      //提交修改
      this.saveForm = {
        id: this.basicForm.id,
        code: this.basicForm.code,
        name: this.basicForm.name,
        location: this.basicForm.location,
        status: this.basicForm.status,
        group_grade_id: this.basicForm.group_grade_id,
        type: this.basicForm.type,
      }
      //查code
      //code查重
      let searchList = await getDeviceGroupList({'code': this.basicForm.code})
      let flag = true
      if (searchList.length > 0) {
        for (let i = 0; i < searchList.length; i++) {
          if (searchList[i].code === this.saveForm.code) {
            flag = false
            break;
          }
        }
      }
      if (flag === false) {
        message.error("设备组编码重复！")
        return
      }

      saveDeviceGroup(this.saveForm).then(async res => {

        if (this.delFalseList.length > 0) {
          for (const delItem of this.delFalseList) {
            await this.delKey1Data(delItem); // 等待每个删除操作完成
          }
        }

        this.handleCancel1()
        //重新加载
        this.query()
      })

    },
    async submitAndSaveDetailMore() {
      this.saveForm = {
        code: this.basicForm.code,
        name: this.basicForm.name,
        location: this.basicForm.location,
        status: this.basicForm.status,
        group_grade_id: this.basicForm.group_grade_id,
        type: this.basicForm.type,
      }
      if (this.saveForm.code === '' || this.saveForm.name === '') {
        message.error('请填写必填项')
        return
      }
      //code查重
      let searchList = await getDeviceGroupList({'code': this.saveForm.code})
      let flag=true
      if(searchList.length>0){
        for (let i = 0; i < searchList.length; i++) {
          if(searchList[i].code===this.saveForm.code) {
            flag = false
            break;
          }
        }
      }
      if(flag===false ){
        message.error("设备组编码重复！")
        return
      }
      saveDeviceGroup(this.saveForm).then(res => {
        //拿group_id
        getDeviceGroupList({'code': this.saveForm.code}).then(res2 => {
          let group_id = res2[0]?.id || ''
          //save关系
          this.addDeviceList.forEach(inItem => {
            saveDeviceGroupRelation({'device_id': inItem.id, 'group_id': group_id})
          })
        })

      }).then(() => {
        message.success('添加成功')
        this.addModal = false
        this.canBeEdited = false
        this.isAdd = false
        this.tabKey = '1'
        this.clearParameters()
        //刷新
        this.query()
      })


    },
    async delSelectGroupData() {
      for (const item of this.selectedRowKeys) {
        // 删除group
        await deleteDeviceGroup({'id': item})
      }
      this.selectedRowKeys=[]
      message.success('删除成功')
      this.query()
    },
    reset() {
      this.queryForm = {
        code: '',
        name: '',
        mask_status: undefined,
      }
      this.query()
    },
    add() {
      this.addDeviceList=[]
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = true
      this.spinning = false
    },
    // 关联子设备
    async getSubDevice(group_id) {
      this.key1Data = []
      this.tableLoading01=true
      //关系
      await getDeviceGroupRelationList({'group_id': group_id}).then(async res => {
        if(res.length===0){
          this.key1Data = []
          this.tableLoading01=false;
        }else{
              res.forEach(it=>{
                getDeviceList({'id': it.device_id}).then(res2 => {
                  if(res2.length===0){
                    this.key1Data = []
                    this.tableLoading01=false;
                  }else{
                    this.key1Data.push(res2[0])
                  }
                })
              })
        }

      }).then(()=>{
        this.tableLoading01=false;

      })
    },

    async subDevice(record) {

      //拿关联的子设备
      this.delFalseList=[]
      this.subModal = true
      this.canBeEdited = true
      this.isAdd = true
      this.spinning = false
      await this.echo(record)
      this.basicForm.create_user_name = await getUserNameById(this.record.create_user)
      await this.getSubDevice(record.id)


    },
    delKey1DataFalse(record){
      //查重
      if (!this.delFalseList.includes(record)) {
        this.delFalseList.push(record);
      }
      //逻辑删
      this.key1Data = this.key1Data.filter(item => item !== record)
    },

    //delKey1Data 删除关联关系
    async delKey1Data(record) {
      let device_id = record.id
      //取出关系id
      console.log({'group_id': this.record.id, 'device_id': device_id})
      await getDeviceGroupRelationList({'group_id': this.record.id, 'device_id': device_id}).then(res2=>{
        res2.forEach(it=>{
           deleteDeviceGroupRelation({'id':it.id})
        })
      }).then(()=>{
        message.success("删除成功")
        //重新加载
        // this.getSubDevice(this.record.id)
      })

    },
    edit(record) {
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = false
      this.echo(record)
    },
    del(id) {
      const params = Object.assign({},{'organization_id': storage.get(ORGANIZATION_ID),'asset_id': id})
      delete_asset(params)
          .then(res => {
            if (res && res.data.code && res.data.code === '1000') {
              this.getAssetLedgerList()
            } else {
              this.$message.error('删除失败',1)
            }
          })
          .catch(err => {
            console.log(err)
            this.$message.error('删除失败',1)
          })
    },
    clearParameter() {},
    handleCancel() {
      this.tabKey = '1'
    },
    async echo(record){
      this.record = record
      const basicProperties = ['code','create_time','create_user','group_grade_id','id',
        'location','name','status','type','status_description']

      for (const item of basicProperties) {
        this.basicForm[item] = record[item]
      }

    },
    submit() {

    },
    // 输入框筛选
  },
  beforeDestroy() {
    if (this.axiosSource) {
      this.axiosSource.cancel('Request canceled due to page navigation.');
    }
  }
}
</script>

<style scoped lang="less">

.aPopover{
}
.aPopover:hover {
  background-color: #EA5413;
}
.dataBox{
  margin-top: 20px;
}
.dataBox{
  margin-top: 20px;
}

.hide-scrollbar::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}

::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}
.hide-scrollbar {
  -ms-overflow-style: none;  /* IE 和 Edge */
  scrollbar-width: none;  /* Firefox */
  overflow-y: scroll; /* 保持内容可滚动 */
}
.demo-infinite-container {
  margin-top: 0px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  padding: 8px 24px;
  height: 300px;
}
/deep/ .ant-form-inline .ant-form-item-with-help{
  margin-bottom: 0px;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #f5f5f5;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .unit .ant-select-selection--single{
  margin-left: 0px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-left: 0;
}
/deep/ .ant-select-disabled .ant-select-selection {
  background-color: #fff;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .ant-input-number-disabled{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
</style>